package com.yfree.datebase;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.yfree.YConfig;

class YDBHelper extends SQLiteOpenHelper {
    private static YDBHelper dbHelper;
    // 表名
    private String[] tableNames = YConfig.YDBTableSQL.tableNames;
    // 建表语句
    private String[] createTableSqls = YConfig.YDBTableSQL.createTableSqls;

    private YDBHelper(Context context, String dbName, int version) {
        super(context, dbName, null, version);
    }

    public static YDBHelper getInstance(Context context, String dbName, int version) {
        if (dbHelper == null)
            dbHelper = new YDBHelper(context, dbName, version);
        return dbHelper;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        if (createTableSqls != null)
            for (String createTableSql : createTableSqls)
                db.execSQL(createTableSql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion < newVersion)
            updateDataBase(db);
    }

    private void updateDataBase(SQLiteDatabase db) {
        if (tableNames != null)
            for (String tableName : tableNames)
                db.execSQL("drop table if exists " + tableName);
        onCreate(db);
    }
}
